﻿using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
using Oracle.ManagedDataAccess.Client;
using Microsoft.AspNetCore.Http;
using Simple.Services.System;
using Simple.Services.System.QHSEUser.Models;

namespace Simple.Services;

public class QHSEUserService
{
    private readonly SimpleDbContext _context;
    public QHSEUserService(SimpleDbContext context)
    {
        _context = context;
    }
    public async Task<List<QHSEUserModel>> GetAsync()
    {
        var users = await _context.Set<QHSESysUser>().AsNoTracking().ToListAsync();
        return MapperHelper.Map<List<QHSEUserModel>>(users);
    }
    public async Task<PageResultModel<QHSEUserModel>> GetPageAsync(QHSEUserPageInputModel input)
    {
        var result = new PageResultModel<QHSEUserModel>();
        var query = _context.Set<QHSESysUser>().AsNoTracking().AsQueryable();

        if (!string.IsNullOrEmpty(input.OrganizationName))
        {
            query = query.Where(u => EF.Functions.Like(u.OrganizationId, $"%{input.OrganizationName}%"));

        }
        if (!string.IsNullOrEmpty(input.Keyword))
        {
            query = query.Where(u => EF.Functions.Like(u.UserName, $"%{input.Keyword}%") || EF.Functions.Like(u.EmployeeNo, $"%{input.Keyword}%"));

        }
        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        query = query.OrderBy(u => u.UserName).Page(input.PageNo, input.PageSize);
        var students = await query.ToListAsync();
        result.Rows = MapperHelper.Map<List<QHSEUserModel>>(students);

        result.SetPage(input);
        result.CountTotalPage();

        return result;
    }
    private static string EscapeLikePattern(string pattern)
    {
        return pattern.Replace("'", "''").Replace("/", "//").Replace("_", "/_").Replace("%", "/%");
    }
    public async Task<PageResultModel<QHSEUserModel>> GetPageResultAsync(QHSEUserPageInputModel input)
    {
        var result = new PageResultModel<QHSEUserModel>();
        var query = _context.Set<QHSESysUser>().AsNoTracking().Join(_context.Set<QHSESysOrganization>(), // Join with Organization table
                            user => user.OrganizationId,
                            organization => organization.OrganizationId,
                            (user, organization) => new { User = user, Organization = organization }).AsQueryable();
        var org =await _context.Set<QHSESysOrganization>().Where(u=>u.OrganizationId == input.OrganizationId).FirstOrDefaultAsync();
        var escapedNamePath = "";
        if (org != null)
        {
            escapedNamePath = EscapeLikePattern(org.NamePath);
        }
        if (!string.IsNullOrEmpty(input.OrganizationName) || string.IsNullOrEmpty(input.OrganizationId))
        {
            query = query.Where(u => EF.Functions.Like(u.Organization.NamePath, $"{escapedNamePath}%", "/"));

        }
        if (!string.IsNullOrEmpty(input.Keyword))
        {
            query = query.Where(u => EF.Functions.Like(u.User.UserName, $"%{input.Keyword}%") || EF.Functions.Like(u.User.EmployeeNo, $"%{input.Keyword}%"));

        }
        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        query = query.OrderBy(u => u.User.UserName).Page(input.PageNo, input.PageSize);
        var users = await query.Select(u=>u.User).ToListAsync();
        var newUsers = MapperHelper.Map<List<QHSEUserModel>>(users);
        foreach( var user in newUsers )
        {
            if (user.OrganizationId != null)
            {
                var organization = await _context.Set<QHSESysOrganization>().FindAsync(user.OrganizationId);
                if (organization != null)
                {
                    user.OrganizationName = organization.NamePath;
                }
            }
            
        }
        result.Rows=newUsers;
        result.SetPage(input);
        result.CountTotalPage();

        return result;
    }
    public async Task<QHSEUserModel> GetUserInfoByMobileAsync(QHSEMobileInputModel input)
    {
        var result = new QHSEUserModel();
        var query = _context.Set<QHSESysUser>().AsQueryable();

        // 根据电话号码查询用户信息
        var user = await query.Where(u => u.Mobile == input.Mobile).FirstOrDefaultAsync();
        if (user != null)
        {
            result = MapperHelper.Map<QHSEUserModel>(user);

            //获取组织名
            result.OrganizationName = await GetOrganizationName(result.UserId);

            return result;
        }
        //用户不存在，返回空值
        return null;
    }
    public async Task<List<QHSEUserModel>> GetUsersAsync(QHSEUserPageInputModel input)
    {
        var result = new List<QHSEUserModel>();
        var query = _context.Set<QHSESysUser>().AsNoTracking().Join(_context.Set<QHSESysOrganization>(),
                                user => user.OrganizationId,
                                organization => organization.OrganizationId,
                                (user, organization) => new { User = user, Organization = organization }).AsQueryable();

        if (!string.IsNullOrEmpty(input.OrganizationName))
        {
            query = query.Where(u => EF.Functions.Like(u.Organization.NamePath, $"%{input.OrganizationName}%"));
        }

        if (!string.IsNullOrEmpty(input.Keyword))
        {
            query = query.Where(u => EF.Functions.Like(u.User.UserName, $"%{input.Keyword}%") || EF.Functions.Like(u.User.EmployeeNo, $"%{input.Keyword}%"));
        }

        var users = await query.Select(u => u.User).ToListAsync();
        var newUsers = MapperHelper.Map<List<QHSEUserModel>>(users);

        foreach (var user in newUsers)
        {
            if (user.OrganizationId != null)
            {
                var organization = await _context.Set<QHSESysOrganization>().FindAsync(user.OrganizationId);
                if (organization != null)
                {
                    user.OrganizationName = organization.NamePath;
                }
            }
        }

        result = newUsers;

        return result;
    }

    public async Task<int> AddAsync(QHSEUserModel model)
    {
        var existingUser = await _context.Set<QHSESysUser>()
            .FirstOrDefaultAsync(u =>u.EmployeeNo == model.EmployeeNo || u.Email == model.Email || u.Mobile == model.Mobile
            || u.IdCard == model.IdCard);

        if (existingUser == null)
        {
            Guid guid = Guid.NewGuid();
            string guidString = RemoveHyphens(guid);

            model.UserId = guidString;
            model.UserFrom = QHSEUserFromType.QHSEVad;
            model.CreateTime = DateTime.Now;
            model.UpdateTime = DateTime.Now;
            var newUser = MapperHelper.Map<QHSESysUser>(model);
            await _context.AddAsync(newUser);
        }
        else
        {
            model.UserId = existingUser.UserId;
            model.UserFrom = QHSEUserFromType.QHSEVad;
            model.UpdateTime = DateTime.Now;
            if( string.IsNullOrEmpty(model.Email))
            {
                model.Email = existingUser.Email;
            }
            if (string.IsNullOrEmpty(model.Mobile))
            {
                model.Mobile = existingUser.Mobile;
            }
            if (string.IsNullOrEmpty(model.IdCard))
            {
                model.IdCard = existingUser.IdCard;
            }
            if(string.IsNullOrEmpty(model.EmployeeNo)) 
            { 
                model.EmployeeNo = existingUser.EmployeeNo;
            }
            var existingMappedUser = MapperHelper.Map<QHSESysUser>(model);
            _context.Entry(existingUser).CurrentValues.SetValues(existingMappedUser);
        }

        return await _context.SaveChangesAsync();
    }

    static string RemoveHyphens(Guid guid)
    {
        return guid.ToString().Replace("-", ""); // 通过 Replace 函数移除连字符 "-"
    }
    public async Task<string> GetOrganizationName(string userId)
    {
        var user =await _context.Set<QHSESysUser>().FindAsync(userId);

        if (user != null)
        {
            var organization = await _context.Set<QHSESysOrganization>().FindAsync(user.OrganizationId);

            if (organization != null)
            {
                return organization.OrganizationName;
            }
        }
        return null;

    }
    public async Task<string> GetNamePath(string userId)
    {
        var user = _context.Set<QHSESysUser>().Where(u => u.UserId == userId).FirstOrDefault();
        var organization = await _context.Set<QHSESysOrganization>().Where(u => u.OrganizationId == user.OrganizationId).FirstOrDefaultAsync();
        if (organization != null)
        {
            return organization.NamePath;
        }
        return null;
    }
}
